<template>
  <div>
    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="practiceList"
      @selection-change="handleSelectionChange"
      border
      stripe
      style="width: 100%;"
      :row-key="row => row.practiceAppointmentId"
    >
      <!-- 表格列内容不变 -->
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="实践项目名称" align="center" prop="practiceAppointmentName" width="180" />
      <el-table-column label="开始时间" align="center" prop="practiceStartTime" width="160">
        <template slot-scope="scope">{{ scope.row.practiceStartTime | formatDateTime }}</template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="practiceEndTime" width="160">
        <template slot-scope="scope">{{ scope.row.practiceEndTime | formatDateTime }}</template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="practiceAddress" width="180" />
      <el-table-column label="教师" align="center" prop="practicalTeacherName" width="100" />
      <el-table-column label="实践状态" align="center" prop="practicalType" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.practicalType === '0' ? 'info' : 'success'">
            {{ scope.row.practicalTypeName || (scope.row.practicalType === '0' ? '未实践' : '已实践') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预约情况" align="center" prop="appointmentType" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.appointmentType === '0' ? 'danger' : 'success'">
            {{ scope.row.appointmentTypeName || (scope.row.appointmentType === '0' ? '已报满' : '未报满') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="限制人数" align="center" prop="restrictionNum" width="100" />
      <el-table-column label="报名人数" align="center" prop="registrationNum" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">{{ scope.row.createTime | formatDateTime }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleViewReservations(scope.row)"
            v-hasPermi="['practice:reservationView']"
          >预约情况</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePagination"
      style="margin-top: 15px"
    />

    <!-- 预约名单子组件 - 点击预约情况后显示 -->
    <div v-if="showReservationList" class="reservation-container">
      <el-divider content-position="left">预约名单</el-divider>
      <ReservationList
        :trainingClassId="classId"
        :practiceAppointmentId="currentPracticeId"
      />
    </div>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { selectListByClassId, removePracticeAppointment } from '@/api/training/practiceAppointment';
// 引入预约名单子组件
import ReservationList from '@/components/class/reservationList.vue'; // 假设子组件路径正确

export default {
  name: 'PracticeTable',
  components: {
    Pagination,
    ReservationList // 注册子组件
  },
  props: {
    classId: {
      type: [String, Number],
      required: true
    }
  },
  filters: {
    formatDateTime(value) {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      const second = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    }
  },
  data() {
    return {
      loading: false,
      total: 0, // 总条数（完整数据的长度）
      practiceList: [], // 当前页数据
      allPracticeList: [], // 完整数据集（保存所有数据）
      queryParams: {
        pageNum: 1, // 当前页码
        pageSize: 10 // 每页条数
      },
      ids: [],
      single: true,
      multiple: true,
      // 新增：控制预约名单显示的变量
      showReservationList: false,
      currentPracticeId: ''
    };
  },
  watch: {
    // 当classId变化时重新加载完整数据并分页
    classId: {
      immediate: true,
      handler() {
        this.getFullList(); // 先获取完整数据
      }
    }
  },
  methods: {
    // 1. 获取完整数据列表（不分页）
    getFullList() {
      this.loading = true;
      selectListByClassId(this.classId).then(res => {
        if (Array.isArray(res)) {
          this.allPracticeList = res; // 保存完整数据
          this.handlePagination(); // 触发分页处理
        } else {
          this.$message.error('获取实践列表失败');
          this.allPracticeList = [];
          this.practiceList = [];
          this.total = 0;
        }
      }).catch(err => {
        console.error('获取实践列表异常：', err);
        this.$message.error('网络异常，请重试');
        this.allPracticeList = [];
        this.practiceList = [];
        this.total = 0;
      }).finally(() => {
        this.loading = false;
      });
    },

    // 2. 处理分页逻辑（根据当前页码和每页条数截取数据）
    handlePagination() {
      const { pageNum, pageSize } = this.queryParams;
      this.total = this.allPracticeList.length; // 总条数为完整数据的长度
      // 计算起始索引和结束索引（数组slice方法：[start, end)）
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      // 截取当前页数据
      this.practiceList = this.allPracticeList.slice(startIndex, endIndex);
    },

    // 选择变化处理
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.practiceAppointmentId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.$emit('selection-change', selection);
    },

    // 编辑操作
    handleEdit(row) {
      this.$emit('edit', row);
    },

    // 查看预约情况 - 修改此方法显示子组件
    handleViewReservations(row) {
      this.currentPracticeId = row.practiceAppointmentId;
      this.showReservationList = true;
      // 滚动到预约名单区域
      this.$nextTick(() => {
        document.querySelector('.reservation-container').scrollIntoView({
          behavior: 'smooth'
        });
      });
    },

    // 删除操作
    handleDelete(row) {
      const ids = row ? [row.practiceAppointmentId] : this.ids;
      if (ids.length === 0) {
        this.$message.warning("请选择需要删除的实践项目");
        return;
      }

      this.$confirm(
        `确定要删除选中的${ids.length}个实践项目吗？删除后数据将无法恢复！`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        removePracticeAppointment(ids).then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.getFullList(); // 删除后重新获取完整数据并分页
            this.ids = [];
            this.single = true;
            this.multiple = true;
            // 如果删除的是当前显示预约名单的项目，隐藏预约名单
            if (ids.includes(this.currentPracticeId)) {
              this.showReservationList = false;
              this.currentPracticeId = '';
            }
          } else {
            this.$message.error(res.msg || "删除失败，请重试");
          }
        }).catch(err => {
          console.error("删除实践异常：", err);
          this.$message.error("网络异常，删除操作失败");
        });
      }).catch(() => {
        this.$message.info("已取消删除操作");
      });
    }
  }
};
</script>

<style scoped>
.el-table {
  background: #fff;
  margin-bottom: 16px;
}

.reservation-container {
  margin-top: 20px;
  padding-top: 10px;
}
</style>
